package com.example.voiceassistant.audio;

import com.example.voiceassistant.config.ConfigManager;
import com.example.voiceassistant.dialog.DialogSessionManager;
import com.example.voiceassistant.monitoring.MonitoringService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 唤醒词检测器，现基于音量 RMS 模拟检测（高音量触发 "AI管家"）。
 * 未来可集成 Porcupine 或 Snowboy 真实唤醒模型。
 */
public class WakeWordDetector implements AudioFrameListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(WakeWordDetector.class);

    private final ConfigManager configManager;
    private final MonitoringService monitoringService;
    private final DialogSessionManager dialogSessionManager;

    public WakeWordDetector(ConfigManager configManager,
                            MonitoringService monitoringService,
                            DialogSessionManager dialogSessionManager) {
        this.configManager = configManager;
        this.monitoringService = monitoringService;
        this.dialogSessionManager = dialogSessionManager;
    }

    @Override
    public void onAudioData(byte[] data) {
        if (data == null || data.length == 0) {
            return;
        }

        // 计算 RMS 音量（类似 AudioCaptureService）
        double rms = 0;
        int bytesRead = data.length;
        for (int i = 0; i < bytesRead; i += 2) {
            if (i + 1 < bytesRead) {
                short sample = (short) ((data[i] & 0xFF) | (data[i + 1] << 8));
                rms += sample * sample;
            }
        }
        rms = Math.sqrt(rms / (bytesRead / 2.0));

        System.out.println("WakeWord RMS: " + rms); // Debug: 打印 RMS 值

        // 模拟唤醒：如果 RMS > 800（高音量），假设检测到唤醒词
        if (rms > 800) {
            String wakeWord = "AI管家"; // 模拟
            monitoringService.counter("wake_word.detected").increment();
            LOGGER.info("模拟检测到唤醒词 '{}', RMS: {}", wakeWord, rms);
            System.out.println("Wake word detected: " + wakeWord); // Debug
            dialogSessionManager.onWakeWordDetected(wakeWord);
        }
    }
}

